export default class WebSocketService {
    constructor(url) {
        this.socket = new WebSocket(url);
        this.listeners = {};
        this.socket.onmessage = this.onMessage.bind(this);
    }

    onMessage(event) {
        const message = JSON.parse(event.data);
        console.log("接收到消息：", message);
        this.callListeners(message);
    }

    callListeners(message) {
        Object.keys(this.listeners).forEach(type => {
            if (message.type === type) {
                this.listeners[type].forEach(listener => listener(message));
            }
        });
    }

    addListener(type, listener) {
        if (!this.listeners[type]) {
            this.listeners[type] = [];
        }
        this.listeners[type][0] = listener;
    }

    removeListener(type, listener) {
        if (this.listeners[type]) {
            this.listeners[type] = this.listeners[type].filter(l => l !== listener);
        }
    }

    close() {
        this.socket.close();
    }
}